package com.ddw.meedeeuh.shared.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * Represents a utilities class for http requests
 * @author cmcnicholas
 *
 */
public abstract class HttpUtils {

	/**
	 * Makes a http request and sends it to a url returning the
	 * response string from the url. This call is blocking
	 * and could take an indeterminate amount of time
	 * @param url the url to make the request to
	 * @return a string response
	 * @throws HttpException if there is a problem generating or making a http request
	 */
	public static String get(String url) throws HttpException {
		if(url == null) {
			throw new IllegalArgumentException("The url cannot be null");
		}

		// Open a connection to the url
		final URLConnection connection;
		try {
			connection = new URL(url).openConnection();
			connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11");
		} catch (MalformedURLException e) {
			throw new HttpException("The url was invalid", e);
		} catch (IOException e) {
			throw new HttpException("Failed to open connection to url: " + url, e);
		}

		// Read the response from the url
		final StringBuilder response = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

			// Buffer the response and append to string builder
			String line;
			while((line = reader.readLine()) != null) {
				response.append(line);
			}
		} catch (IOException e) {
			throw new HttpException("Failed to get or read input stream from url: " + url, e);
		} finally {
			try {
				if(reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				throw new HttpException("Failed to close stream for url: " + url, e);
			}
		}

		return response.toString();
	}

	/**
	 * Method to url encode a string value
	 * @param value the value to encode
	 * @return an encoded string
	 * @throws HttpException if the encoding type is not supported, this should never happen
	 */
	public static String encode(String value) throws HttpException {
		try {
			return URLEncoder.encode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new HttpException("Failed to encode value", e);
		}
	}

}
